import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/home/view/drive/signature_A_page.dart';
import 'package:yuan_hang_app/views/home/view/drive/signature_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../base/full_base_page.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_dimens.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/w_toast.dart';

class ContractLocckPage extends StatefulWidget {
  Map driveInfo;

  ContractLocckPage({super.key, required this.driveInfo});

  @override
  BaseState<ContractLocckPage> createState() => _ContractLocckPageState();
}

class _ContractLocckPageState extends BaseState<ContractLocckPage> {
  late final WebViewController _controller;

  String url = "";
  List<Map> saleManList = WConstant().salesmanList;

  int progress = 0;

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "试驾协议预览",
        rightWidget: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // GestureDetector(
              //   onTap: () {
              //     CommonDialog.showConformDialog(
              //       context: context,
              //       title: "提示",
              //       content: "即将进行甲方签名，是否继续",
              //       onConfirm: (text) {
              //         RouteHelper.pushWidget(context,
              //                 SignatureAPage(driveInfo: widget.driveInfo))
              //             .then((value) {
              //           if (value != null) {
              //             RouteHelper.maybePop(context, value);
              //           }
              //           setState(() {});
              //         });
              //       },
              //     );
              //   },
              //   child: Row(
              //     children: [
              //       Image.asset(
              //         "images/ic_msg_read.png",
              //         width: 12.px,
              //       ),
              //       SizedBox(
              //         width: 3.px,
              //       ),
              //       WText(
              //         "甲方",
              //         style: TextStyle(
              //           color: WColors.mainTextColor,
              //           fontSize: WDimens.tsSmall,
              //         ),
              //       ),
              //     ],
              //   ),
              // ),
              GestureDetector(
                onTap: () {
                  CommonDialog.showConformDialog(
                    context: context,
                    title: "提示",
                    content: "即将进行乙方签名，是否继续",
                    onConfirm: (text) {
                      RouteHelper.pushWidget(context,
                          SignaturePage(driveInfo: widget.driveInfo))
                          .then((value) {
                        if (value != null) {
                          RouteHelper.maybePop(context, value);
                        }
                        setState(() {});
                      });
                    },
                  );
                },
                child: Row(
                  children: [
                    Image.asset(
                      "images/ic_msg_read.png",
                      width: 12.px,
                    ),
                    SizedBox(
                      width: 3.px,
                    ),
                    WText(
                      "签名",
                      style: TextStyle(
                        color: WColors.mainTextColor,
                        fontSize: WDimens.tsSmall,
                      ),
                    ),
                  ],
                ),
              ),
            ]),
        child: progress < 100
            ? Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const CircularProgressIndicator(
                      color: WColors.primaryColor,
                    ),
                    SizedBox(
                      height: 10.px,
                    ),
                    WText(
                      "加载中...",
                      style: TextStyle(
                          color: WColors.mainTextColor,
                          fontSize: WDimens.tsLarge),
                    )
                  ],
                ),
              )
            : WebViewWidget(
      controller: _controller,
    )

       );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(
            const PlatformWebViewControllerCreationParams());
    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int p) {
            progress = p;
            setState(() {});
            print('-----------------(progress : $progress%)');
          },
          onPageStarted: (String url) {
            print('------------------Page started loading: $url');
          },
          onPageFinished: (String url) {
            print('------------------Page finished loading: $url');
          },
        ),
      );
    _controller = controller;
    // _controller.loadRequest(Uri.parse(
    //     "http://59.48.146.131:29180/document/view?viewToken=e54bf102-e2a5-4a12-90c6-3c5418f1969d"));
    getDriveContractLock();
  }

  void getDriveContractLock() {
    var driveInfo = Map.from(widget.driveInfo);
    //   showLoading();
    driveInfo["saleMan"] = CommonReqUtils.exchangeCodeToName2(
            saleManList, widget.driveInfo["saleMan"]) ??
        "";
    HttpUtils()
        .post(Api.getTestDriveContractLock, data: widget.driveInfo)
        .then((data) {
      if (data.resultCode == 200) {
        //调用_controller.future.then方法来异步处理一个未来值。当未来值可用时，它会调用一个回调函数，该回调函数接收这个值作为参数（命名为value）
        url = data.data;
        _controller.loadRequest(Uri.parse(url));
        Toast.toast("获取试驾协议成功");
      } else {
        Toast.toast(data.errMsg ?? "");
      }
    });
  }
}
